package com.anxinr.util;

import com.alibaba.fastjson.JSON;
import com.anxinr.enums.ExceptionEnum;
import com.anxinr.exception.LogicException;
import com.anxinr.pojo.dto.UserDTO;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * redis 工具类
 *
 * @author anxinr
 */
@Slf4j
@Component
public class RedisUtil {
    @Autowired
    private StringRedisTemplate redisTemplate ;
    /**
     * 缓存用户信息  并设置过期时间
     * @param userTokenInfo
     * @param user
     * @param minutes
     * @param userTokenInfoTime
     */
    public void setUserInfo(String userTokenInfo, UserDTO user, TimeUnit minutes, Long userTokenInfoTime) {
        redisTemplate.opsForValue().set(userTokenInfo,JSON.toJSONString(user),userTokenInfoTime,minutes) ;
    }
    public UserDTO getUserInfo(String token) {
        String user = redisTemplate.opsForValue().get(token);
        if (StringUtils.isBlank(user)){
            throw new LogicException(ExceptionEnum.STUDY_INVALID_LOGIN_ERROR) ;
        }
        return JSON.parseObject(user, UserDTO.class);
    }
}
